package com.itheima.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.util.concurrent.ScheduledFuture;

/**
 * @author 何杰
 * @date 11/3/2023 11:27 PM
 */

@Service
public class DynamicSchedulerService {
    private ThreadPoolTaskScheduler scheduler;
    private ScheduledFuture<?> scheduledFuture;
    @Autowired
    private EmailController controller;
    @Autowired
    private EmailService emailService;

    public DynamicSchedulerService(ThreadPoolTaskScheduler scheduler){
        this.scheduler=scheduler;
    }
    public void startScheduledTask(String cronExpression){
        stopScheduledTask();
        Runnable task = () ->{
            emailService.sendSimpleEmail(controller.emailusername,controller.emailtitle,controller.emailtext);
        };
        scheduledFuture = scheduler.schedule(task,new CronTrigger(cronExpression));
    }
    public void stopScheduledTask(){
        if (scheduledFuture != null && !scheduledFuture.isCancelled()){
            scheduledFuture.cancel(true);//取消旧的定时任务
        }
    }

}
